package de.medizin.uni.halle.irm;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.actionbarsherlock.app.SherlockFragmentActivity;

public class MailSystem extends javax.mail.Authenticator {
	public static String from, user, password, rserver, rport, protocoll, sendserver,sendport, receiveserver,receiveport;
    private final Session sendsession;
	private static SQLiteDatabase database;
	static DateFormat date;

    public MailSystem(SherlockFragmentActivity sherlockFragmentActivity)  {
    	database = sherlockFragmentActivity.openOrCreateDatabase("born", Context.MODE_PRIVATE, null);
    	Cursor c = database.rawQuery("SELECT * FROM settings", null);
    	
    	c.moveToPosition(4);
    	from = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	user = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	password = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	receiveserver = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	receiveport = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	protocoll = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	sendserver = c.getString(c.getColumnIndex("parameter"));
    	c.moveToNext();
    	sendport = c.getString(c.getColumnIndex("parameter"));
    	
        Properties sendprops = new Properties();

        
        sendprops.setProperty("mail.smtp.host", sendserver);
        sendprops.put("mail.smtp.auth", "true");
        sendprops.put("mail.smtp.port", sendport);        
        sendsession = Session.getInstance(sendprops,this);
        date = new SimpleDateFormat("y-MM-d H:mm:ss");
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
      
    public boolean sendEmail(String subject, String body, String recipients) throws Exception {
    	
        Message msg = new MimeMessage( sendsession );
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom( addressFrom );
        InternetAddress addressTo = new InternetAddress(recipients);
        msg.setRecipient( Message.RecipientType.TO, addressTo );
        msg.setSubject( subject );
        msg.setContent( body, "text/plain" );
       
        if (recipients.indexOf(',') > 0)
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        
         Transport.send(msg); // TODO: aktivieren. geht nur nicht lokal wegen Medi-Firewall
         return true;
    }
    public boolean getMails(SherlockFragmentActivity sherlockFragmentActivity ) {
    	try {		
	        Properties receiveprops = new Properties(); 
	        if(protocoll.equals("pop3")){
	        	receiveprops.setProperty( "mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory" );
		        receiveprops.put("mail.pop3.auth", "true");
		        receiveprops.put("mail.pop3.port", "995" );    
	        }
	        else if(protocoll.equals("imap")){
	        	receiveprops.setProperty( "mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory" );
		        receiveprops.put("mail.imap.port", "993" );   
		        receiveprops.put("mail.imap.auth", "true");
	        }
	        Session receivesession = Session.getInstance(receiveprops);
		    Store store = receivesession.getStore( protocoll );
		    store.connect(receiveserver, user , password);
		    Folder folder = store.getFolder( "INBOX" );
		    folder.open( Folder.READ_WRITE);
		    storeMessages(folder, sherlockFragmentActivity);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
    }
    
    public static void storeMessages( Folder folder, SherlockFragmentActivity sherlockFragmentActivity ) throws MessagingException, IOException
	{
    	database = sherlockFragmentActivity.openOrCreateDatabase("born", Context.MODE_PRIVATE, null);
    	for ( Message m : folder.getMessages() ){
    		Cursor c = database.rawQuery("SELECT * FROM patients WHERE email =\"" +
					((InternetAddress) m.getFrom()[0]).getAddress()+"\";",null);
			if(c.getCount()>0){
	    		if ( m.isMimeType( "text/plain" ) ){	
	    			ContentValues initialValues = new ContentValues();
    				c.moveToFirst();
    				initialValues.put("sid", c.getString(c.getColumnIndex("sid")));        							
				    initialValues.put("historytype", "email received");
				    initialValues.put("type", "email");
				    initialValues.put("content", m.getContent().toString());		    	
				    initialValues.put("date", date.format(m.getSentDate()).toString());
				    database.insert("history", null, initialValues); 	
				    m.setFlag(Flags.Flag.DELETED, true);
				}
	    		else if ( m.isMimeType( "multipart/*" ) ){
	    			Multipart mp = (Multipart) m.getContent();
	    			if ( mp.getCount() > 1 ){
	    				Part part = mp.getBodyPart( 0 );
	    				System.out.println( part.getContent() );
	        			ContentValues initialValues = new ContentValues();
	        			c.moveToFirst();
	        			initialValues.put("sid", c.getString(c.getColumnIndex("sid")));        				
	    			    initialValues.put("historytype","email received");
	    			    initialValues.put("type", "email");
	    			    initialValues.put("content", part.getContent().toString());		    	
	    			    initialValues.put("date", date.format(m.getSentDate()).toString());
	    			    database.insert("history", null, initialValues); 
	    			    m.setFlag(Flags.Flag.DELETED, true);	    			    
	    			}
	    			for ( int j = 1; j < mp.getCount(); j++ )
	    			{
	    				Part part = mp.getBodyPart( j );
	    				String disp = part.getDisposition();
	    				if ( disp == null || disp.equalsIgnoreCase( Part.ATTACHMENT ) ){
	    					MimeBodyPart mimePart = (MimeBodyPart) part;
	    					System.out.println( "MIME-Typ ist " + mimePart.getContentType() );
	    					if ( mimePart.isMimeType( "text/xml" ) )
	    						System.out.println( mimePart.getContent() );
	    					}
	    			}
	    			System.out.println( "Verarbeitung abgeschlossen" );
	    		}
	    	}else
	    		System.out.println("Mail konnte nicht zugeordnet werden");
    	}
    	folder.close(true);
    	database.close();
	}
}
